# import time
# from urllib.parse import parse_qs
# from urllib.parse import quote
#
# import requests
# from fastapi.requests import Request
# from fastapi import APIRouter, HTTPException
# from jose import jwt
# from starlette.responses import JSONResponse, Response
#
# from models.m import User
# from tool.jwt_utils import create_access_token, create_refresh_token
#
# dsf = APIRouter()
#
# @dsf.get("/baidu")
# async def baidu():
#     """
#     获取钉钉OAuth授权URL
#     注意：回调地址需要与钉钉开放平台配置一致
#     """
#     # 正确的回调地址：后端接口地址
#     # 注意：这里使用127.0.0.1而不是localhost，要与钉钉平台配置一致
#     redirect_uri = 'http://127.0.0.1:8000/user/dingding'
#
#     params = [
#         f"redirect_uri={quote(redirect_uri)}",
#         "response_type=code",
#         "client_id=dingqxjco4n5jjtt7ctj",
#         "scope=openid",
#         "prompt=consent"
#     ]
#     url = "https://login.dingtalk.com/oauth2/auth?" + ("&".join(params))
#
#     return JSONResponse({"url": url})
#
# #百度回调接口http://127.0.0.1:8000/user/dingding
# @dsf.get("/dingding")
# async def dingding(request: Request):
#     """
#     获取服务器信息
#     """
#     # 获取当前登录用户
#     query_string = request.url.query
#     query_params = parse_qs(query_string.decode() if isinstance(query_string, bytes) else query_string)
#     authCode = query_params.get('code', [None])[0]
#
#     if not authCode:
#         raise HTTPException(status_code=400, detail="Missing authorization code")
#
#     data = {
#         "clientId": "dingqxjco4n5jjtt7ctj",
#         "clientSecret": "cQJnGlcoMmz6Nnv-r0aFEpQAHqiwVK0t4yf1J_9Do8jQP1AV81iVT2M3GXHWLy53",
#         "code": authCode,
#         "grantType": "authorization_code"
#     }
#
#
#
#     resp = requests.post('https://api.dingtalk.com/v1.0/oauth2/userAccessToken', json=data).json()
#     accessToken = resp.get('accessToken')
#     uid = resp.get('openId')
#
#     headers = {"x-acs-dingtalk-access-token": accessToken}
#
#     resp = requests.get('https://api.dingtalk.com/v1.0/contact/users/me', headers=headers).json()
#
#     name = resp.get('nick')
#     phone = resp.get('mobile')
#
#     #     # 登录，写入三方登录表和用户表
#     #     # 查询该钉钉用户是否已绑定系统账户
#
#     #插入数据库
#     user = await User.filter(phone=phone).first()
#     if not user:
#         user = await User.create(
#             nickname=name, phone=phone,
#             role = 1, password_hash = '123456'
#         )
#         await user.save()
#
#         # 创建新用户的token
#         token = create_access_token(data={"user_id": user.id, "phone": user.phone, "nickname": user.nickname})
#         refreshToken = create_refresh_token(data={"user_id": user.id, "phone": user.phone, "nickname": user.nickname})
#
#         return {
#             "message": "登录成功",
#             "status": "success",
#             "data": {
#                 "token": token,
#                 "refreshToken": refreshToken,
#                 "user": {
#                     "id": user.id,
#                     "phone": user.phone,
#                     "nickname": user.nickname,
#                     "avatar_url": user.avatar_url,
#                     "role": int(user.role),
#                     "status": int(user.status)
#                 }
#             }
#         }
#
#     # 已存在用户，创建token
#     token = create_access_token(data={"user_id": user.id, "phone": user.phone, "nickname": user.nickname})
#     refreshToken = create_refresh_token(data={"user_id": user.id, "phone": user.phone, "nickname": user.nickname})
#
#     return {
#         "message": "登录成功",
#         "status": "success",
#         "data": {
#             "token": token,
#             "refreshToken": refreshToken,
#             "user": {
#                 "id": user.id,
#                 "phone": user.phone,
#                 "nickname": user.nickname,
#                 "avatar_url": user.avatar_url,
#                 "role": int(user.role),
#                 "status": int(user.status)
#             }
#         }
#     }
#
#
# # 刷新token函数需要修正
# @dsf.get("/refresh")
# async def refresh(request: Request):
#     # 从查询参数获取token而不是request.data
#     query_string = request.url.query
#     query_params = parse_qs(query_string.decode() if isinstance(query_string, bytes) else query_string)
#     token = query_params.get('retoken', [None])[0]
#
#     if not token:
#         raise HTTPException(status_code=400, detail="Missing token")
#
#     try:
#         # 使用正确的JWT解码方法
#         data = jwt.decode(token, "your-secret-key", algorithms=["HS256"])
#     except jwt.JWTError:
#         raise HTTPException(status_code=401, detail="Invalid token")
#
#     payload = {"userid": data['userid'], "username": data['username'], "exp": int(time.time()) + 60 * 60 * 2}
#     # 使用正确的JWT编码方法
#     new_token = jwt.encode(payload, "your-secret-key", algorithm="HS256")
#     payload["exp"] = int(time.time() + 60 * 60 * 24 * 2)
#     refreshToken = jwt.encode(payload, "your-secret-key", algorithm="HS256")
#
#     # 返回JSONResponse而不是Response，并使用正确的userid来源
#     return JSONResponse({
#         "code": 200,
#         'token': new_token,
#         "userid": data['userid'],
#         "retoken": refreshToken
#     })




























